package com.moon.ws;

/**
 * @author Chenzy
 * @create 2023-03-30 19:00
 */
import com.moon.dto.Item;
import com.moon.dto.TUser;
import com.moon.utils.JsonUtils;
import com.moon.utils.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.CrossOrigin;

import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/webSocket/{auctionId}/{token}")
@Component
@CrossOrigin("*")
public class WebSocket {

    private static Map<Integer, Map<String,WebSocket>> clients = new ConcurrentHashMap();
    private Session session;
    private String account;

    private List<Item> list = new ArrayList<>();

    @OnOpen
    public void onOpen(@PathParam("auctionId") Integer auctionId,@PathParam("token") String token, Session session) {

        try{
            TUser user = JwtUtils.getObject(token, TUser.class);
            if (user == null){
                return;
            }
            this.account = user.getAccount();
            this.session = session;
            if (!clients.containsKey(auctionId)){
                clients.put(auctionId,new HashMap<String, WebSocket>());
            }
            clients.get(auctionId).put(this.account,this);
        }catch (Exception e){

        }
    }

    @OnClose
    public void onClose() {
        clients.remove(account);
    }


    //接受前端send的消息
    @OnMessage
    public void onMessage(String message) {
        System.out.println(message);
        Double step = 500.0;

        Item item = JsonUtils.toObj(message, Item.class);
        //项目这里需要查询数据库，拿到List<AuctionItemVo>,判断message中的金额是不是阶梯提升的
        if ( list.size() > 0 && ((item.getPrice() - list.get(0).getPrice()) < 0 || (item.getPrice() - list.get(0).getPrice())%step != 0)){
            System.out.println("竞拍金额有误，请调整金额！");
            return;
        }

        //如果是，则把message写入 数据库，同时更新List<AuctionItemVo>
        List<Item> temp = new ArrayList<>();
        temp.add(item);
        temp.addAll(list);
        list = temp;

        String auctionId = this.session.getPathParameters().get("auctionId");
        System.out.println(this);
        //然后发送List<AuctionItemVo>给该竞拍室id的所有session
        sendMessage(JsonUtils.toJson(list),Integer.parseInt(auctionId));


    }

    @OnError
    public void onError(Session session, Throwable throwable) {
        System.out.println("error:" + throwable.getMessage());
    }


    //向前端onmessage发送String消息
    public static void sendMessage(String message , Integer auctionId) {
        // 向所有连接websocket的客户端发送消息
        // 可以修改为对某个客户端发消息
        for (WebSocket item : clients.get(auctionId).values()) {
            item.session.getAsyncRemote().sendText(message);
        }
    }


}